package com.faiz.algorithm;

import java.util.*;

public class TopKFrequent {
    public int[] topKFrequent(int[] nums, int K) {
        // 当前的基本思路，使用快排的思想
        // 首先获取到出现次数表，然后通过出现次数进行排序
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.putIfAbsent(num, 0);
            map.computeIfPresent(num, (k, v) -> v + 1);
        }
        List<int[]> values = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            values.add(new int[]{entry.getValue(), entry.getKey()});
        }
        quickSort(values, 0, values.size() - 1, K);
        int[] res = new int[K];
        for (int i = 0; i < K; i++) {
            res[i] = values.get(i)[1];
        }
        return res;
    }

    public void quickSort(List<int[]> values, int start, int end, int k) {
        // 获取随机数
        int picked = (int) (Math.random() * (end - start + 1)) + start;
        Collections.swap(values, picked, start);

        int pivot = values.get(start)[0];
        int index = start;
        for (int i = start + 1; i <= end; i++) {
            if (values.get(i)[0] >= pivot) {
                Collections.swap(values, index + 1, i);
                index++;
            }
        }

        Collections.swap(values, index, start);

        if (index > k - 1) {
            quickSort(values, start, index - 1, k);
        } else if (index < k - 1){
            quickSort(values, index + 1, end, k);
        }

    }

    public static void main(String[] args) {
        int[] nums = {1, 1, 1, 2, 2, 3};
        TopKFrequent topKFrequent = new TopKFrequent();
        System.out.println(Arrays.toString(topKFrequent.topKFrequent(nums, 2)));
    }
}
